package com.ay.weixin.autoreply.event.handle;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Cell;
import org.lizar.ioc.Container;
import org.lizar.json.JObject;
import org.lizar.log.Log;
import org.lizar.log.Logger;

import com.ay.weixin.autoreply.db.IbatisAutoReplyDao;
import com.ay.weixin.autoreply.domain.LastMessage;
import com.ay.weixin.autoreply.domain.Message;
import com.ay.weixin.config.ProjectConfig;

public class HandleTextMsg implements Cell{

	private Log log=Logger.newInstance(this.getClass());
	
	public Map<String,LastMessage> reply_cache=new HashMap<String,LastMessage>();
	private IbatisAutoReplyDao reply_dao;
	
	private HandleMsg handle_msg;
	
	@Override
	public void init_property() throws Exception {
		reply_dao=Container.get(IbatisAutoReplyDao.class);
		handle_msg=Container.get(HandleMsg.class);
		
			}
	
	public void handle_text_msg(EventLoader el,long wxproject_id,JObject msg) throws IOException{
		String from_user=msg.getStr("from_user_name");
		LastMessage lmsg=reply_cache.get(from_user);
		Message matched_input=null;
		
		if(lmsg==null){
			try {
				//not matched, then search from level 1
				matched_input=reply_dao.getTopMatchedInput(wxproject_id,msg.getStr("content"));
			} catch (SQLException e) {
				e.printStackTrace();
				return;
			}
		}else{
			try {
				//search from parent
				matched_input=reply_dao.getParentMatchedInput(wxproject_id,msg.getStr("content"),lmsg.getId());
				if(matched_input==null){
					matched_input=reply_dao.getTopMatchedInput(wxproject_id,msg.getStr("content"));
				}
			} catch (SQLException e) {
				e.printStackTrace();
				return;
			}
		}
		
		if(matched_input==null){
			if(ProjectConfig._bool(wxproject_id,"weixin_api_auto_reply.default_msg_reply")){
				handle_auto_reply(el,wxproject_id,msg);
			}
			if(lmsg!=null){
				reply_cache.clear();
			}
			
		}else{
			if(lmsg==null){
				lmsg=new LastMessage();
			}
			lmsg.setAct("query");
			lmsg.setId(matched_input.getId());
			lmsg.setTimestamp(System.currentTimeMillis());
			lmsg.setFrom_user_name(from_user);
			reply_cache.put(from_user, lmsg);
			handle_msg.reply(wxproject_id,matched_input,el,msg);
		}
		
	}
	


	public void handle_auto_reply(EventLoader el,long wxproject_id,JObject msg) throws IOException{
		
		Message default_msg=null;
		
		try {
			default_msg=reply_dao.getDefaultTextMsgReply(wxproject_id);
		} catch (SQLException e) {
			e.printStackTrace();
			return;
		}
		
		if(default_msg==null){
			log.warn("weixin_api_auto_reply.default_msg_reply=true but don't set any default reply message body yet.");
		}else{
			handle_msg.reply(wxproject_id,default_msg,el,msg);
		}
		
	}
	

}
